package com.gardenguell.salad.helper;

import com.gardenguell.salad.util.CommonLog;

import java.io.*;
import java.net.*;

/**
 * Created by absurd on 14-3-11.
 */
public class UdpClientSocket {
    public static final int SOCKET_TIME_OUT_LONG = 15000;
    public static final int SOCKET_TIME_OUT_SHORT = 5000;
    private CommonLog log = CommonLog.getInstance();
    private byte[] buffer = new byte[1024];

    private DatagramSocket ds = null;


    public UdpClientSocket() throws Exception {
        ds = new DatagramSocket();
        ds.setSoTimeout(SOCKET_TIME_OUT_LONG);
    }

    public DatagramPacket send(final String host, final int port,
                                     final byte[] bytes) throws IOException {
        DatagramPacket dp = new DatagramPacket(bytes, bytes.length, InetAddress
                .getByName(host), port);
        ds.send(dp);
        return dp;
    }

    /**
     *
     * @return when Timeout or IOException return null
     */
    public String receive(int timeOut){
        DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
        String info = "";
        try {
            ds.setSoTimeout(timeOut);
            ds.receive(dp);
            info = new String(dp.getData(), 0, dp.getLength());
        }catch(SocketTimeoutException e){
            e.printStackTrace();
            log.e("Socket time out");
        } catch (IOException e) {
            e.printStackTrace();
            log.e("socket io exception");
        }
        return info;
    }

    public void close() {
        try {
            ds.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}